package com.cscec5b.inspection.config;

// ✅ 正确的包名
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Refill;

import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class RateLimiterService {
    private final Map<String, Bucket> buckets = new ConcurrentHashMap<>();
    private final AppProperties props;

    public RateLimiterService(AppProperties props) { this.props = props; }

    public boolean tryConsume(String clientId) {
        Bucket b = buckets.computeIfAbsent(clientId, id -> {
            Bandwidth bw = Bandwidth.classic(
                    props.getRateLimitPerMin(),
                    Refill.intervally(props.getRateLimitPerMin(), Duration.ofMinutes(1))
            );
            return Bucket.builder().addLimit(bw).build();
        });
        return b.tryConsume(1);
    }
}
